package hr.mlab.app.expenses.activities.type;

import hr.mlab.app.expenses.AppGlobals;
import hr.mlab.app.expenses.DatabaseOpenHelper;
import hr.mlab.app.expenses.R;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class TypeGroupList extends ListActivity {
    private EditText type;
    private Integer  typeId;
    private SQLiteDatabase db;
    private Cursor cursorGroup;
    private ListAdapter adapter;
    private int cursorPosition;
    private Boolean fromItemClick=false;
   
    /** Called when the activity is first created. */
    @Override    
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.typegrouplist);
    	db = (new DatabaseOpenHelper(this)).getReadableDatabase();
    	type = (EditText) findViewById (R.id.type);
    	
    	typeId = getIntent().getIntExtra("typeId", 0);
    	fillListView();
    }

    /**
     * Closing activity
     */
    @Override    
    public void onDestroy() {
    	super.onDestroy();
    	cursorGroup.close();
    	db.close();
    }
    
    /**
     * Filling list
     */
    public void fillListView() {
    	Cursor cursorType = db.rawQuery("SELECT typeName FROM " + DatabaseOpenHelper.dbTypes +
    						 			 " WHERE _id = ?", new String[]{typeId.toString()}); 
    	
		if (cursorType.getCount() == 1)
		{
			cursorType.moveToFirst();

			type.setText(cursorType.getString(cursorType.getColumnIndex("typeName")));
		}
		else {
			Toast.makeText(this, this.getString(R.string.error_noData), Toast.LENGTH_LONG).show();
			finish();
		}

		cursorType.close();
		
    	// || is the concatenation operation in SQLite
		if(cursorGroup != null)
			if(!cursorGroup.isClosed())
				cursorGroup.close();
		
    	cursorGroup = db.rawQuery("SELECT _id, groupName FROM " + DatabaseOpenHelper.dbGroups + " as c " +
    						 " JOIN " + DatabaseOpenHelper.dbTypeGroups + " as gc " +
    						 " ON gc.groupId = c._id where gc.typeId = ? ", 
                             new String[]{typeId.toString()});
    	
		if (cursorGroup.getCount() < 1)
		{
			Toast.makeText(this, this.getString(R.string.error_noData), Toast.LENGTH_LONG).show();
			finish();
		}
		
        adapter = new SimpleCursorAdapter(
                            this, 
                            R.layout.typegrouprow, 
                            cursorGroup, 
                            new String[] {"groupName"}, 
                            new int[] {R.id.groupTypeName});
        
        setListAdapter(adapter);
        registerForContextMenu(getListView());
     }

    /**
     * Catcher of list clicks
     * @param ListView parent, View view, int position, long id
     */
    public void onListItemClick(ListView parent, View view, int position, long id) {
    	cursorPosition = position;
       	fromItemClick = true;
       	((Activity) this).openOptionsMenu();
    }
    
 	/**
 	 * Menu initialization
 	 * @param menu
 	 */
 	@Override
 	public boolean onCreateOptionsMenu(Menu menu) {
 		MenuInflater inflater = getMenuInflater();
 		inflater.inflate(R.menu.newmenu, menu);
 		return true;
 	}
 	
 	/**
 	 * Changing a menu. We don't have fixed menu. It's changed depending on where it opens 
 	 * @param menu
 	 */
 	@Override
 	public boolean onPrepareOptionsMenu(Menu menu) {
 		menu.clear();
 		if(fromItemClick) {
 			menu.add(0, AppGlobals.optDelete, 0, this.getString(R.string.btnDelete));
 			menu.add(0, AppGlobals.optNew, 0, this.getString(R.string.btnNew));
 		} else {
 			menu.add(0, AppGlobals.optNew, 0, this.getString(R.string.btnNew)); 			
 		}
 		
 		fromItemClick = false;
 		
 		return super.onPrepareOptionsMenu(menu);
 	}

 	/**
 	 * Reaction to the menu selection
 	 * @param featureId, menuItem
 	 */
 	@Override
 	public boolean onMenuItemSelected(int featureId, MenuItem item) {
 		return super.onMenuItemSelected(featureId, item);
 	}

 	/**
 	 * Reaction to the option menu selection
 	 * @param menuItem
 	 */
 	@Override
 	public boolean onOptionsItemSelected(MenuItem item) {
		callGroupDetail(item.getItemId());
 		return super.onOptionsItemSelected(item);
 	}
 	
 	/**
 	 * Reaction to the context menu selection
 	 * @param menuItem
 	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		callGroupDetail(item.getItemId());
		return super.onContextItemSelected(item);
	}
	
	/**
	 * we need a handler when the secondary activity finishes it's work
	 * and returns control to this activity...
	 * @param requestCode, resultCode, intent
	 */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    	super.onActivityResult(requestCode, resultCode, intent);
    	if(resultCode == Activity.RESULT_OK ) { 
    		fillListView();
    		setSelection(intent.getIntExtra("groupId", 0));
    	}
    }

    /**
     * Calling detail for group
     * @param menuitem - indicates option
     */
	public void callGroupDetail(int menuitem){
		// Intent is used for sending parameters to new window
    	Intent intent = new Intent(this, TypeGroupDetail.class);
    	intent.putExtra("option", (byte) menuitem);
    	intent.putExtra("typeId", typeId);
    	
    	// If we aren't inserting new row, we need to know id from item we are looking in new window
    	if(menuitem > 1) {
    		Cursor cursor = (Cursor) adapter.getItem(cursorPosition);
    		intent.putExtra("groupId", cursor.getInt(cursor.getColumnIndex("_id")));
    	} else {
    		intent.putExtra("groupId", 0);
    	}
    	
    	// with startActivity we don't expecting return, 
    	// because of that we are using startActivityForResult
    	startActivityForResult(intent, menuitem);
	}
}
